package com.javablog.controller;

import com.javablog.dto.UserDto;
import com.javablog.dto.response.MessageResponse;
import com.javablog.model.User;
import com.javablog.repository.UserRepository;
import com.javablog.security.services.UserDetailsImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;
import java.util.stream.Collectors;

@CrossOrigin(origins = "*", maxAge = 3600)
@RestController
@RequestMapping("/api/users")
public class UserController {
    
    @Autowired
    private UserRepository userRepository;
    
    @Autowired
    private PasswordEncoder encoder;
    
    @GetMapping("/me")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> getCurrentUser() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        User user = userRepository.findById(userDetails.getId())
                .orElseThrow(() -> new RuntimeException("错误：用户未找到。"));
        
        UserDto userDto = convertToDto(user);
        
        return ResponseEntity.ok(userDto);
    }
    
    @GetMapping("/{id}")
    public ResponseEntity<?> getUserById(@PathVariable Long id) {
        User user = userRepository.findById(id)
                .orElseThrow(() -> new RuntimeException("错误：用户未找到。"));
        
        UserDto userDto = convertToDto(user);
        
        return ResponseEntity.ok(userDto);
    }
    
    @PutMapping("/me")
    @PreAuthorize("hasRole('USER') or hasRole('ADMIN')")
    public ResponseEntity<?> updateCurrentUser(@Valid @RequestBody UserDto userDto) {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        UserDetailsImpl userDetails = (UserDetailsImpl) authentication.getPrincipal();
        
        User user = userRepository.findById(userDetails.getId())
                .orElseThrow(() -> new RuntimeException("错误：用户未找到。"));
        
        if (userDto.getUsername() != null && !user.getUsername().equals(userDto.getUsername())) {
            if (userRepository.existsByUsername(userDto.getUsername())) {
                return ResponseEntity
                        .badRequest()
                        .body(new MessageResponse("错误：用户名已被使用!"));
            }
            user.setUsername(userDto.getUsername());
        }
        
        if (userDto.getEmail() != null && !user.getEmail().equals(userDto.getEmail())) {
            if (userRepository.existsByEmail(userDto.getEmail())) {
                return ResponseEntity
                        .badRequest()
                        .body(new MessageResponse("错误：邮箱已被使用!"));
            }
            user.setEmail(userDto.getEmail());
        }
        
        if (userDto.getAvatar() != null) {
            user.setAvatar(userDto.getAvatar());
        }
        
        if (userDto.getBio() != null) {
            user.setBio(userDto.getBio());
        }
        
        userRepository.save(user);
        
        return ResponseEntity.ok(new MessageResponse("用户信息更新成功!"));
    }
    
    @GetMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> getAllUsers() {
        List<User> users = userRepository.findAll();
        List<UserDto> userDtos = users.stream()
                .map(this::convertToDto)
                .collect(Collectors.toList());
        
        return ResponseEntity.ok(userDtos);
    }
    
    @DeleteMapping("/{id}")
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<?> deleteUser(@PathVariable Long id) {
        if (!userRepository.existsById(id)) {
            return ResponseEntity
                    .badRequest()
                    .body(new MessageResponse("错误：用户未找到!"));
        }
        
        userRepository.deleteById(id);
        
        return ResponseEntity.ok(new MessageResponse("用户删除成功!"));
    }
    
    private UserDto convertToDto(User user) {
        UserDto userDto = new UserDto();
        userDto.setId(user.getId());
        userDto.setUsername(user.getUsername());
        userDto.setEmail(user.getEmail());
        userDto.setAvatar(user.getAvatar());
        userDto.setBio(user.getBio());
        userDto.setEnabled(user.isEnabled());
        userDto.setCreatedAt(user.getCreatedAt());
        userDto.setUpdatedAt(user.getUpdatedAt());
        userDto.setArticleCount(user.getArticles().size());
        userDto.setCommentCount(user.getComments().size());
        userDto.setSubscriberCount(user.getSubscribers().size());
        userDto.setRoles(user.getRoles().stream()
                .map(role -> role.getName().name())
                .collect(Collectors.toSet()));
        
        return userDto;
    }
} 